package com.xiangyueEducation.uploaderCloud.controller;
import com.xiangyueEducation.uploaderCloud.constant.RedisConstant;
import com.xiangyueEducation.uploaderCloud.pojo.dto.PageQuery;
import com.xiangyueEducation.uploaderCloud.pojo.entity.Modules;
import com.xiangyueEducation.uploaderCloud.pojo.vo.PageVo;
import com.xiangyueEducation.uploaderCloud.service.ModuleService;
import com.xiangyueEducation.uploaderCloud.utils.JwtHelper;
import com.xiangyueEducation.uploaderCloud.utils.Result;
import com.xiangyueEducation.uploaderCloud.utils.enums.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/module")
public class ModuleController {

    @Autowired
    private ModuleService moduleService;
    @Autowired
    private JwtHelper jwtHelper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @PostMapping("/teacher")
    public Result addModule(@RequestBody Modules moduleDTO, @RequestHeader("token") String token){
        //获取用户id
        Long userId = jwtHelper.getUserId(token);
        stringRedisTemplate.delete(RedisConstant.MODULE_CACHE_KEY);
        return moduleService.insert(moduleDTO,userId);
    }

    //配置缓存原因：像试题模块这样的数据，不会轻易修改，一旦被查询接下来很有可能经常查询
    //学生和老师都可以看到全部试题，但学生可以做题，老师可以改题目
    //因为是学校的题库，因此，必须是分页的
    // 布隆过滤器防止缓存穿透
    //不配置缓存击穿，因为不符合被高并发访问并且缓存重建业务比较复杂的概念
    @GetMapping("/all")
    public Result getModules(PageQuery pageQuery){
        Result result = pageQuery.checkPage();
        if (result!=null){
            return result;
        }
        PageVo pageVo = moduleService.queryModules(pageQuery);

        return Result.ok(pageVo);
    }
    // 修改模块
    @PutMapping("/teacher")
    public Result updateModule(@RequestBody Modules moduleDTO){
        moduleService.updateById(moduleDTO);
        stringRedisTemplate.delete(RedisConstant.MODULE_CACHE_KEY);
        return Result.ok(ResultCodeEnum.SUCCESS);
    }
    // 删除模块
    @DeleteMapping("/teacher")
    public Result deleteModule(Long moduleId){
        //删除模块，也要连带着试题一起删除了
        moduleService.removeWithQuestion(moduleId);
        stringRedisTemplate.delete(RedisConstant.MODULE_CACHE_KEY);
        return Result.ok(ResultCodeEnum.SUCCESS);
    }


}
